<template>
  <div class="department-container">
    <div class="app-container">
      <page-tools title="总记录数：20条">
        <el-button
          v-allow="'import_excel'"
          type="warning"
          size="small"
          @click="$router.push('/employees/import')"
        >excel导入</el-button>
        <el-button
          v-allow="'export_excel'"
          type="danger"
          size="small"
          @click="hExportxlsx"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="showDialog = true"
        >新增员工</el-button>
      </page-tools>

      <el-card style="margin-top: 10px">
        <el-table border :data="arr">
          <el-table-column label="序号" type="index" width="70px" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" type="index" width="180px">
            <template slot-scope="scope">
              <ImageHolder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="mobile" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 优化聘用形式 -->
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id=' + scope.row.id)"
              >查看</el-button>
              <el-button
                type="text"
                size="small"
                @click="hjueshe(scope.row.id)"
              >分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="q.page"
            :page-sizes="[5, 10, 15, 20]"
            :page-size="q.size"
            layout="total, sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
    </div>

    <el-dialog
      title="添加"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="resetFrom"
    >
      <em-dialog ref="refEmdialog" @success="hSuccess" />
    </el-dialog>

    <el-dialog
      title="分配角色"
      :visible.sync="showDialogRole"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <assign-role
        v-if="showDialogRole"
        :cur-id="curId"
        @success="hSuccessRole"
      />
    </el-dialog>
  </div>
</template>

<script>
// 定义一个聘用状态的变量
import { TYPE_MAP } from '@/consted/changliang'
import { getEmployeeList, delEmployee } from '@/api/employees'
import emDialog from './empDialog.vue'
import AssignRole from './assignRole.vue'
export default {
  components: { emDialog, AssignRole },
  data() {
    return {
      arr: [],
      q: {
        page: 1,
        size: 5
      },
      total: 0,
      showDialog: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    // 子组件点击保存添加角色返回的事件
    hSuccessRole() {
      // 1.关闭弹窗
      this.showDialogRole = false
    },
    // 给子组件发送当前选中的员工的id
    hjueshe(id) {
      this.showDialogRole = true
      this.curId = id
    },
    // 处理后端返回的数据方便导出xlsx
    formatData(list) {
      const zhkeys = {
        id: '编号',
        mobile: '手机号',
        username: '用户名',
        password: '密码',
        timeOfEntry: '聘用日期',
        formOfEmployment: '聘用形式',
        workNumber: '工号',
        correctionTime: '转正日期',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 获取中文表头
      const header = Object.values(zhkeys)
      const data = list.map((item) => {
        if (item.formOfEmployment) {
          item.formOfEmployment = TYPE_MAP[item.formOfEmployment] || '未知'
        }
        return Object.values(item)
      })
      return { header, data }
    },
    // 导出xlsx
    async hExportxlsx() {
      const res = await getEmployeeList(this.q)
      const { header, data } = this.formatData(res.data.rows)
      console.log(header, data)
      import('@/vendor/Export2Excel').then((excel) => {
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    // 获取员工信息
    async getEmployee() {
      const res = await getEmployeeList(this.q)
      //   console.log(res)
      this.arr = res.data.rows
      this.total = res.data.total
    },
    // 格式化应聘状态
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    // 每页的条数
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`)
      this.q.size = val
      this.q.page = 1
      this.getEmployee(this.q)
    },
    // 当前页码
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`)
      this.q.page = val
      this.getEmployee(this.q)
    },
    // 删除员工
    hDel(id) {
      this.$confirm('此操作将永久删除，确认继续吗？', '提示', {
        type: 'warning'
      })
        .then(() => {
          this.doDel(id)
        })
        .catch(() => {})
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        this.$message.success(res.message)
        if (this.arr.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.getEmployee()
      } catch (error) {
        this.$message.warning(error)
      }
    },
    hSuccess() {
      // 关闭弹窗
      this.showDialog = false
      this.total++
      this.q.page = Math.ceil(this.total / this.q.size)
      // 重新渲染数据
      this.getEmployee()
    },
    // 重置表单
    resetFrom() {
      this.$refs.refEmdialog.resetForm()
    }
  }
}
</script>
